package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.RuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author marcher
 */
public abstract class AbstractRuleNacosPublisher<T> implements DynamicRulePublisher<T> {

    @Resource
    private ConfigService configService;

    /**
     * 发布配置到 nacos
     *
     * @param entities
     */
    protected void publishConfig(String app, List<? extends RuleEntity> entities) throws NacosException {
        AssertUtil.notEmpty(app, "app name cannot be empty");
        if (CollectionUtils.isEmpty(entities)) {
            return;
        }

        String dataId = buildDataId(app);
        configService.publishConfig(dataId, SentinelNacosConstants.GROUP_ID, SentinelNacosConvert.convertToRule(entities));
    }

    /**
     * 构建 dataId
     *
     * @param appName   appName
     * @return
     */
    private String buildDataId(String appName) {
        return appName + postfix();
    }

    /**
     * 后缀
     *
     * @return
     */
    abstract protected String postfix();

}
